<template>
  <div>
    <div class="chat-container">
      <div class="message-list">
        <div v-for="(message, index) in messages" :key="index" class="message">
          {{ message }}
        </div>
      </div>
      <div class="input-area">
        <input v-model="newMessage" placeholder="Type a message..." />
        <button @click="sendMessage">客户端发送</button>
        <button @click="sendMessageToServer">服务端发送</button>
        <button @click="connectWebSocket">建立连接</button>
        <button @click="disconnectWebSocket">断开连接</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';
import {websocketSendService} from '@/api/websocket.js';

export default {
  setup() {
    const ws = ref(null);
    const messages = ref([]);
    const newMessage = ref('');

    const connectWebSocket = () => {
      ws.value = new WebSocket('ws://localhost:8080/ws/' + Math.random().toString(36).substr(2));

      ws.value.onopen = () => {
        alert('WebSocket connected')
      };

      ws.value.onmessage = event => {
        messages.value.push(event.data);
      };
    };

    const disconnectWebSocket = () => {
      if (ws.value) {
        ws.value.close();
        alert('WebSocket disconnected');
      }
    };

    //客户端发送消息
    const sendMessage = () => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        ws.value.send(newMessage.value);
        messages.value.push('客户端: ' + newMessage.value);
        newMessage.value = '';
      } else {
        console.error('WebSocket is not open');
      }
    };

    //服务端发送消息
    async function sendMessageToServer() {
      try {
        let response = await websocketSendService(newMessage.value);
        // 处理接收到的响应
      } catch (error) {
        console.error('发生错误:', error);
        // 在这里可以处理错误的情况，如显示错误提示或者进行其他逻辑
      }
    }

    return {
      messages,
      newMessage,
      connectWebSocket,
      disconnectWebSocket,
      sendMessage,
      sendMessageToServer
    };
  }
};
</script>

<style>
.chat-container {
  max-width: 400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.message-list {
  margin-bottom: 10px;
  overflow-y: scroll;
  max-height: 200px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.input-area {
  display: flex;
  align-items: center;
}

input {
  flex: 1;
  padding: 5px;
  margin-right: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  background-color: #007bff;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
}
</style>
